angular.module('Controller')
.controller 'QgyOnlineCheckCtrl',($scope,$http,urls,$rootScope,menuManage,NgTableParams,commonConstant,wfAlert,$uibModal,$localStorage)->
    $scope.sexList=commonConstant.qgySexList()
    $scope.person={
        idcardFront:'images/id_card_front.jpg'
        idcardBack:'images/id_card_back.jpg'
        frontUploaded:false
        backUploaded:false
    }
    $scope.checkIn={
        receptionist:undefined
        buzType:1
        inviteCode:undefined
        contractPicture:undefined
    }
    $scope.search={
        filter:undefined
    }
    $scope.channelTypeList = commonConstant.chiChannelTypeList()
    loadIdCard=()->
        back=$scope.contractData?.idcardBack
        front=$scope.contractData?.idcardFront
        imgReg=/^.*[^a][^b][^c]\.(?:png|jpg|bmp|gif|jpeg)$/
        if front && imgReg.test(front)
            $scope.person.idcardFront=front
            $scope.person.frontUploaded=true
        if back && imgReg.test(back)
            $scope.person.idcardBack=back
            $scope.person.backUploaded=true
    bandUpdateEvent=()->
        $('#on-idcard-front').unbind()
        $('#on-idcard-front').change(()->
            fileName=$('#on-idcard-front').eq(0).val()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#on-idcard-front')[0].files[0])
            $http({
                url:urls.backend+urls.imageUploadTo+"/image?token="+$localStorage['token'],
                method:'POST'
                headers:{
                    'Content-Type': undefined
                }
                data:formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code==0
                    saveUrl = resp.message.saveUrl+""
                    if(saveUrl.indexOf("http")==0)
                        $scope.person.idcardFront = saveUrl
                    else
                        $scope.person.idcardFront=urls.backend+'/public/'+saveUrl
            )
        )
        $('#on-idcard-back').unbind()
        $('#on-idcard-back').change(()->
            fileName=$('#on-idcard-back').eq(0).val()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#on-idcard-back')[0].files[0])
            $http({
                url:urls.backend+urls.imageUploadTo+"/image?token="+$localStorage['token'],
                method:'POST'
                headers:{
                    'Content-Type': undefined
                }
                data:formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code==0
                    saveUrl = resp.message.saveUrl+""
                    if(saveUrl.indexOf("http")==0)
                        $scope.person.idcardBack = saveUrl
                    else
                        $scope.person.idcardBack=urls.backend+'/public/'+saveUrl
            )
        )
    $scope.tableData=[]
    $scope.tableParams = new NgTableParams(
            {page: 1, count: commonConstant.pageTableCount},
            {
                counts:[]
                getData: ($defer, params)->
                    console.log('filter',$scope.search.filter)
                    if $scope.search.filter
                        reqData={
                            page:params.page() - 1
                            size:params.count()
                            status:4
                            searchStr:$scope.search.filter
                        }
                        $scope.doQuery(reqData,$defer,params)
                    else
                        $scope.tableData=[]
                        params.total(0)
                        $defer.resolve($scope.tableData)
                    return ;
            }
    )
    $scope.doQuery=(reqData,$defer, params)->
        $http.get('/contract',params:reqData)
        .success (resp)->
            if resp.code==0
                $scope.tableData=resp.message.content
                params.total(resp.message.totalElements)
                $defer.resolve($scope.tableData)
                if resp.message.content.length==1
                    loadContract(resp.message.content[0].id)
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    loadContract=(id)->
        $http.get("/contract/#{id}/detail")
        .success((resp)->
            if resp.code==0
                $scope.contractData=resp.message
                $scope.search.filter=undefined
                $scope.tableParams.reload()
                if $scope.contractData.cotenants==undefined
                    $scope.contractData.cotenants=[]
                _.defer(()->
                    console.log('线上入住绑定身份证上传事件')
                    bandUpdateEvent()
                    loadIdCard()
                )
        )
    _.extend $scope,
        searchContract:()->
            $scope.tableParams.reload()
        pickContract:(item)->
            loadContract(item.id)
        resetContract:()->
            $scope.contractData=undefined
        uploadIDCFront:()->
            $('input[id=on-idcard-front]').click();
            ''
        uploadIDCBack:()->
            $('input[id=on-idcard-back]').click();
            ''
        onlineCheckIn:()->
#            if !$scope.person.backUploaded || !$scope.person.frontUploaded
#                wfAlert.toastError('请上传身份证正反面')
#                return
            reqData={
                idcardFront:$scope.person.idcardFront
                idcardBack:$scope.person.idcardBack
                receptionist: $scope.checkIn.receptionist
                buzType: $scope.checkIn.buzType
                inviteCode:$scope.checkIn.inviteCode
                contractPicture:$scope.checkIn.contractPicture
            }
            console.log($scope.contractData)
            $http.post("/contract/checkIn/#{$scope.contractData.id}",reqData)
            .success((resp)->
                if resp.code==0
                    $rootScope.$broadcast('refresh')
                    $scope.contractData.checked=true
                    $scope.contractData.status=8
                    wfAlert.toastInfo('入住成功')
                else
                    wfAlert.toastError(resp.message)
            )
        openCotenant:(type,item)->
            modal=showCotenantModal(type,item)
            modal.result.then((modalData)->
                if modalData && type!='view'
                    item=modalData
            )
            ''
        printContract:()->
            if $scope.contractData and $scope.contractData.contractPdf
                window.open($scope.contractData.contractPdf, '_blank')
            else
                wfAlert.toastError('合同pdf文件未生成')
            ''
        editContract:()->
            if $scope.contractData.status in [2,4]
                $rootScope.pageType='contract-edit'
                $rootScope.pageParams=angular.copy({contractId:$scope.contractData.id})
                menuManage.goState('contract-edit',true)
    showCotenantModal=(type,data)->
        modal = $uibModal.open({
            animation: true,
            size:'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantModalCtrl',
            templateUrl: 'templates/business-manage/cotenant-modal/cotenant-modal.html',
            resolve: {
                items:  ()->{type:type,data:data}
            }
        })
    if $rootScope.pageType=='online-check'
        loadContract($rootScope.pageParams.contractId)
        $rootScope.pageParams=undefined
        $rootScope.pageType=undefined
    $rootScope.$on('refresh',(val,data)->
        if $scope.contractData and data.contractId==$scope.contractData.id
            loadContract(data.contractId)
    )
